package com.banmoon.sync;

/**
 * 同步后的买票服务，线程安全
 */
public class SyncTicketServer implements Runnable{

    private int ticketNum = 10;

    /**
     * 取票
     */
    @Override
    public void run() {
        // 获取当前线程名
        String name = Thread.currentThread().getName();
        while (true){
            // 注意，锁住的是this对象哦，也就是32行创建出来的ticketServer
            synchronized (this){
                if(ticketNum<=0)
                    return;
                System.out.println(name + "：取到了第" + ticketNum + "张票");
                // 模拟网络延迟
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                ticketNum--;
            }
        }
    }

    public static void main(String[] args) {
        SyncTicketServer ticketServer = new SyncTicketServer();
        new Thread(ticketServer, "A").start();
        new Thread(ticketServer, "B").start();
        new Thread(ticketServer, "C").start();
    }
}
